﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class EditCursorAction : MonoBehaviour
{
    public RectTransform workingArea;
    public ConfigDraw configUI;

    const float kMinSize = 0.5f;
    const float kMaxSize = 6f;
    float size = 1.0f;

    Vector2 originSize;
    float canvasScale;
    // Start is called before the first frame update
    void Start()
    {
        originSize = workingArea.sizeDelta;
        lastMousePos = Input.mousePosition;
        canvasScale = workingArea.GetComponentInParent<Canvas>().transform.localScale.x;
    }

    Vector3 lastMousePos;
    // Update is called once per frame
    void Update()
    {
        if (EventSystem.current.IsPointerOverGameObject()) return;

        var scr = Input.GetAxisRaw("Mouse ScrollWheel");
        if (scr != 0)
        {
            size += scr * size;
            size = Mathf.Clamp(size, kMinSize, kMaxSize);

            var pos = (Vector2)workingArea.InverseTransformPoint(Input.mousePosition) + workingArea.anchoredPosition;

            var currentPivot = workingArea.pivot;
            var currentSizeD = workingArea.sizeDelta;

            workingArea.pivot = GetRelativePosition(workingArea.offsetMin, workingArea.offsetMax, pos);
            var offset = Vector2.Scale(workingArea.pivot - currentPivot, currentSizeD);
            workingArea.anchoredPosition += offset;

            workingArea.sizeDelta = originSize * size;
            //configUI.Draw();
        }

        if(Input.GetMouseButtonDown(2))
        {
        }
        else if (Input.GetMouseButton(2))
        {
            Vector2 delta = Input.mousePosition - lastMousePos;
            workingArea.anchoredPosition += delta/canvasScale;
            //configUI.Draw();

        }

        lastMousePos = Input.mousePosition;
    }

    Vector2 GetRelativePosition(Vector2 min, Vector2 max, Vector2 test)
    {
        return new Vector2(
            (test.x - min.x) / (max.x - min.x),
            (test.y - min.y) / (max.y - min.y)
            );
    }
}
